﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Org.BouncyCastle.Ocsp;
using System;
using System.Linq.Expressions;
using System.Threading.Tasks;
using WebApi.Helpers;
using WebApi.Model;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MonitorController : BaseController
    {
        public MonitorController(ILogger<MonitorController> logger) : base(logger)
        {
        }

        /// <summary>
        /// 获取监磅数据(根据车牌号获取最新一条)
        /// </summary>
        /// <param name="plate">车牌号</param>
        /// <param name="flag">称重状态（0时读取第一次监磅数据，1时读取第二次监磅数据）</param>
        /// <returns></returns>
        [HttpGet]
        public ReturnModel Get(string plate, int flag)
        {
            try
            {
                logger.LogInformation($"Monitor/Get:plate={plate},flag={flag}");
                ReturnModel returnModel = new ReturnModel();
                returnModel.Data = DbHelper.GetDbConn().Queryable<Monitor>().Where(it => it.Plate == plate && it.Flag == flag).OrderBy(it => it.Id, SqlSugar.OrderByType.Desc).First();
                returnModel.Count = returnModel.Data == null ? 0 : 1;
                return returnModel;
            }
            catch (Exception ex)
            {
                LogToDB("Monitor", "查询", $"参数：plate={plate},flag={flag}", "异常", $"{nameof(Get)}-{ex.Message}");
                return logger.ErrorModel(nameof(MonitorController) + "-" + nameof(Get), ex);
            }
        }

        /// <summary>
        /// 获取监磅数据分页列表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("GetPageList")]
        public async Task<ReturnModel> GetPageList(QueryMonitorVM model)
        {
            try
            {
                Expression<Func<Monitor, bool>> filter = e => true;
                if (!string.IsNullOrEmpty(model.Plate))
                    filter = filter.And(c => c.Plate.Contains(model.Plate));
                if (!string.IsNullOrEmpty(model.GoodsName))
                    filter = filter.And(c => c.GoodsName.Contains(model.GoodsName));
                //if (model.BeginTime != null)
                //    filter = filter.And(c => SqlSugar.SqlFunc.DateIsSame(Convert.ToDateTime(c.GrossTime), model.BeginTime));
                //if (model.EndTime != null)
                //    filter = filter.And(c => SqlSugar.SqlFunc.DateIsSame(Convert.ToDateTime(c.TareTime),model.EndTime));
                if (model.BeginTime != null)
                    filter = filter.And(c => model.BeginTime <= c.AddTime);
                if (model.EndTime != null)
                    filter = filter.And(c => model.EndTime >= c.AddTime);
                SqlSugar.PageModel pageModel = new SqlSugar.PageModel { PageIndex = model.PageIndex, PageSize = model.PageSize };
                var data = await DbHelper.Monitor.GetPageListAsync(filter, pageModel);
                return new ReturnModel { Count = pageModel.TotalCount, Data = data };
            }
            catch (Exception ex)
            {
                LogToDB("Monitor", "查询", $"参数：{JsonConvert.SerializeObject(model)}", "异常", $"{nameof(GetPageList)}-{ex.Message}");
                return logger.ErrorModel($"{nameof(MonitorController)}/{nameof(GetPageList)}", ex);
            }
        }

        /// <summary>
        /// 获取监磅数据列表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost("GetList")]
        public async Task<ReturnModel> GetList(QueryMonitorVM model)
        {
            try
            {
                Expression<Func<Monitor, bool>> filter = e => true;
                if (!string.IsNullOrEmpty(model.Plate))
                    filter = filter.And(c => c.Plate.Contains(model.Plate));
                if (!string.IsNullOrEmpty(model.GoodsName))
                    filter = filter.And(c => c.GoodsName.Contains(model.GoodsName));
                //if (model.BeginTime != null)
                //    filter = filter.And(c => SqlSugar.SqlFunc.DateIsSame(Convert.ToDateTime(c.GrossTime), model.BeginTime));
                //if (model.EndTime != null)
                //    filter = filter.And(c => SqlSugar.SqlFunc.DateIsSame(Convert.ToDateTime(c.TareTime),model.EndTime));
                if (model.BeginTime != null)
                    filter = filter.And(c => model.BeginTime <= c.AddTime);
                if (model.EndTime != null)
                    filter = filter.And(c => model.EndTime >= c.AddTime);
                var data = await DbHelper.Monitor.GetListAsync(filter);
                return new ReturnModel { Count = data.Count, Data = data };
            }
            catch (Exception ex)
            {
                LogToDB("Monitor", "查询", $"参数：{JsonConvert.SerializeObject(model)}", "异常", $"{nameof(GetList)}-{ex.Message}");
                return logger.ErrorModel($"{nameof(MonitorController)}/{nameof(GetList)}", ex);
            }
        }


        /// <summary>
        /// 删除监磅数据（数据超差时重置）
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost("Reset")]
        public async Task<ReturnModel> Reset([FromForm] int id)
        {
            Monitor model = null;
            try
            {
                logger.LogInformation($"Monitor/Reset:{id}");
                model = await DbHelper.Monitor.GetFirstAsync(it => it.Id == id);
                ReturnModel returnModel = new ReturnModel();
                if (model != null)
                {
                    if (string.IsNullOrEmpty(model.GrossTime) || (!string.IsNullOrEmpty(model.TareTime) && Convert.ToDateTime(model.GrossTime) < Convert.ToDateTime(model.TareTime)))
                    {
                        model.TareWeight = null;
                        model.TareTime = null;
                    }
                    else if (string.IsNullOrEmpty(model.TareTime) || Convert.ToDateTime(model.GrossTime) >= Convert.ToDateTime(model.TareTime))
                    {
                        model.GrossTime = null;
                        model.GrossWeight = null;
                    }
                    returnModel.Count = await DbHelper.Monitor.UpdateAsync(model) ? 1 : 0;
                }
                return returnModel;
            }
            catch (Exception ex)
            {
                LogToDB("Monitor", "重置", $"参数：id={id},更新的数据 ：{JsonConvert.SerializeObject(model ?? new Monitor())}", "异常", $"{nameof(Reset)}-{ex.Message}");
                return logger.ErrorModel(nameof(MonitorController) + "-" + nameof(Reset), ex);
            }
        }
    }
}
